﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseComponent;

public partial class FoldersControlEN : System.Web.UI.UserControl
{

    //declaring event on selected item changed

    


    public delegate void SelectedItemChangedDel(object sender, CustomEventArgs e);

    public event SelectedItemChangedDel SelectedItemChanged = null;


    protected void RaiseSelectedItemChanged(CustomEventArgs e)
    {
        if (SelectedItemChanged != null)
            SelectedItemChanged(this, e);
    }


    //end of declaring event


    protected void Page_Load(object sender, EventArgs e)
    {
        

        if (!Page.IsPostBack)
        {
            if (dtlFolders.DataSource == null)
            {
                bindList();
            }


            if (trNew.Nodes.Count == 0)
                bindTree();

        }




    }




    /// <summary>
    /// This function will bind the tree with all folders
    /// </summary>
    private void bindTree()
    {
        //throw new NotImplementedException();

        FoldersDB fdb = new FoldersDB(ConnectionStrings.LMS);
        List<Folders> lstFolders = fdb.Select("", " where ( [ParentID] IS NULL OR [ParentID] = '-1' ) AND [StatusID] <> '2' ");
        
        trNew.DataSource = new FoldersHierList (lstFolders) ;

        trNew.PathSeparator = '/';
        
        
        trNew.DataBind();

        trNew.CollapseAll();


    }

    /// <summary>
    /// this function will get the selected value
    /// </summary>
    /// <returns>the selected value</returns>
    public long get()
    {
        try
        {
            return long.Parse(hdID.Value);
        }
        catch
        {
            return -1;
        }

    }


    
    
    


    /// <summary>
    /// this function will set the control to a folder
    /// </summary>
    /// <param name="valID">the ID of the folder to set</param>
    public void set(long valID)
    {
        bindControls(valID);

        
    }


    /// <summary>
    /// this function will select a node in the tree by its ID
    /// </summary>
    /// <param name="ID">the ID to select node with</param>
    protected void selectNodeByID(long ID)
    {
        if (trNew.Nodes.Count == 0)
            bindTree();

        selectNodeStart(trNew, ID);
    }



    /// <summary>
    /// this will bind the list with the root folder
    /// </summary>
    protected void bindList()
    {
        //lblPath.Text = "/";
        hdID.Value = "-1";
        FoldersDB objFoldersDB = new FoldersDB(ConnectionStrings.LMS);
        List<Folders> lstFolders = objFoldersDB.Select ("", " where [ParentID] is null ");

        //lstFolders = new List<Folders>(from objFol in lstFolders where objFol.StatusID != 2 select objFol);
              

        

        Folders objFolders = new Folders();
        objFolders.ID = -1;
        CustomEventArgs e = new CustomEventArgs(false, objFolders);
        RaiseSelectedItemChanged(e);
        if (e.Cancel)
            return;
        dtlFolders.DataSource = lstFolders;
        dtlFolders.DataBind();
    }



    protected void dtlFolders_ItemEditing(object sender, ListViewEditEventArgs e)
    {
        e.Cancel = true;
        long ID = long.Parse(dtlFolders.DataKeys[e.NewEditIndex]["ID"].ToString());

        bindControls(ID);

       



        

    }


    /// <summary>
    /// this function will expand the treenode recursive
    /// </summary>
    /// <param name="tn">the tree node to expand</param>
    protected static void expandTreeNode(TreeNode tn)
    {
        tn.Expand();
        if (tn.Parent != null)
            expandTreeNode(tn.Parent);
        
    }



    /// <summary>
    /// this function will start a recursive tree parsing
    /// </summary>
    /// <param name="tr">the tree to parse</param>
    /// <param name="ID">an ID to find</param>
    /// <returns></returns>
    protected static bool selectNodeStart(TreeView tr, long ID)
    {
        tr.CollapseAll();   
        for (int i = 0; i < tr.Nodes.Count; i++)
        {
            if (selectNode(tr.Nodes[i], ID))
                return true;
        }


        return false;
    }


    /// <summary>
    /// this function will parse tree recursive to get the node
    /// </summary>
    /// <param name="tn">the node to search in</param>
    /// <param name="ID">the id to search for</param>
    /// <returns>true if node selected</returns>
    protected static  bool selectNode(TreeNode tn, long ID)
    {
        if (long.Parse(tn.Value) == ID)
        {
            expandTreeNode(tn);
            tn.Select();

            return true;
        }

        for (int i = 0; i < tn.ChildNodes.Count; i++)
        {
            
            if (selectNode(tn.ChildNodes[i], ID))
                return true;

        }

        return false;
    }




    /// <summary>
    /// this function will bind controls with the folder with ID
    /// </summary>
    /// <param name="ID">the ID of the folder to set</param>
    protected void bindControls(long ID)
    {
        string strNewID = "";
        string strNewPath = "";

        


        if (ID == -1)
        {
            bindList();
            selectNodeByID(-1);
            return;
        }


        FoldersDB objFoldersDB = new FoldersDB(ConnectionStrings.LMS);
        List<Folders> lstFolders = objFoldersDB.getFoldersByID(ID);

        //lstFolders = new List<Folders>(from objFol in lstFolders where objFol.StatusID != 2 select objFol);


        if (lstFolders.Count == 0)
        {
            bindList();
            selectNodeByID(-1);
            return;
        }


        List<Folders> lstBind = lstFolders[0].lstChild;

        lstBind.Insert(0, new Folders());

        if (lstFolders[0].ParentID != null)
        {
            lstBind[0].ID = lstFolders[0].ParentID.Value;
            lstBind[0].ParentID = lstFolders[0].ParentID;
        }
        else
        {
            lstBind[0].ID = -1;
            lstBind[0].ParentID = null;
        }

        lstBind[0].FolderNameAR = "..";
        lstBind[0].FolderNameEN = "..";


        if (lstFolders[0].FolderNameEN == "..")
        {
            if (lstFolders[0].ParentID != null)
            {
                strNewPath = lstFolders[0].objParent.PathEN;
                strNewID = lstFolders[0].objParent.ID.ToString();
                CustomEventArgs e = new CustomEventArgs(false, lstFolders[0].objParent);

                RaiseSelectedItemChanged(e);
                if (e.Cancel)
                    return;
            }
            else
            {
                strNewPath = "/";
                strNewID = "-1";
                Folders objFolders = new Folders();
                objFolders.ID = -1;
                CustomEventArgs e = new CustomEventArgs(false, objFolders);
                RaiseSelectedItemChanged(e);
                if (e.Cancel)
                    return;
            }



        }
        else
        {
            strNewPath = lstFolders[0].PathEN;
            strNewID = lstFolders[0].ID.ToString();
            CustomEventArgs e = new CustomEventArgs(false, lstFolders[0]);
            RaiseSelectedItemChanged(e);

            if (e.Cancel)
                return;
        }


        //lblPath.Text = strNewPath;
        hdID.Value = strNewID;

        selectNodeByID(long.Parse(hdID.Value));
        dtlFolders.DataSource = lstBind;
        dtlFolders.DataBind();
    }

    protected void trNew_SelectedNodeChanged(object sender, EventArgs e)
    {
        set(long.Parse(trNew.SelectedValue));

        
    }



    /// <summary>
    /// this function will refresh the tree contents after delete, save
    /// </summary>
    public void refreshTree()
    {
        bindTree();
        bindControls(get());


    }


    /// <summary>
    /// this function to get image for style in binding
    /// </summary>
    /// <param name="strImage">the image full url</param>
    /// <returns>an url coated by  {'} </returns>
    public string getBackImage(string strImage)
    {
        return "\'" + strImage + "\'";
    }

    /// <summary>
    /// this function will get the name of the folder or back for return
    /// </summary>
    /// <param name="dataitem">the folder object from container.dataitem</param>
    /// <returns>a string containing the name</returns>
    protected string getFolderNameBack(object dataitem)
    {
        Folders folder = (Folders)dataitem;

        if (folder.FolderNameEN == "..")
            return "Back";
        else
            return folder.FolderNameEN;
    }
}
